//
//  SearchViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/26.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTitleView.h"
#import "SearchCell.h"
#import "Utility.h"
#import "UIScrollView+EmptyDataSet.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>


#define kSearchCellIdentifier @"SearchCellIdentifier"

@interface SearchViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate
>

{
    NSString *keyword;
}

@property (nonatomic, strong) SearchTitleView *searchView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) UIActivityIndicatorView *loadingView;
@property (nonatomic, strong) UILabel *loadingLabel;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) MJRefreshNormalHeader *header;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, assign) BOOL isEmpty;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIColor *textColor;
    if (@available(iOS 13.0, *)) {
        UIColor *titleColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kTextBlackColor;
            } else {
                return UIColor.secondaryLabelColor;
            }
        }];
        textColor = titleColor;
    } else {
        textColor = kTextBlackColor;
    }
    
    [self setRightItemTitle:@"取消" titleColor:textColor action:@selector(cancelAction)];
    
    [self setupSearchView];
    
    [self.tableView registerNib:NIB_NAMED(@"SearchCell") forCellReuseIdentifier:kSearchCellIdentifier];
    self.isEmpty = YES;
}

//- (void)setTableView:(UITableView *)tableView
//{
//    _tableView = tableView;
//    _tableView.emptyDataSetSource = self;
//    _tableView.emptyDataSetDelegate = self;
//}


//#pragma mark - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate -
//
//- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
//    return [UIImage imageNamed:@"list_empty"];
//}
//
//- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
//    NSString *title = @"暂无数据";
//    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:COLOR_RGB(186, 186, 186)};
//    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
//}
//
//- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
//    return [UIColor groupTableViewBackgroundColor];
//}

- (void)setupSearchView
{
    if (@available(iOS 13.0, *)) {
        self.navigationController.navigationBar.standardAppearance.backgroundColor = UIColor.tertiarySystemBackgroundColor;
    } else {
        self.navigationController.navigationBar.barTintColor = UIColor.whiteColor;
    }

    self.searchView = [[SearchTitleView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth*0.8, 30)];
    self.searchView.layer.masksToBounds = YES;
    self.searchView.layer.cornerRadius = 15;
    self.navigationItem.titleView = self.searchView;
    
    @weakify(self);
    self.searchView.textFieldBlock = ^(NSString *keywords){
        @strongify(self);
        keyword = keywords;
        NSString *temp = [keywords stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (temp.length) {
            self.isEmpty = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 关键字搜索
                [self searchWithKeyword:keywords];
            });
        } else {
            self.isEmpty = YES;
            [self.dataSource removeAllObjects];
            [self.tableView reloadData];
        }
    };
}

- (void)searchWithKeyword:(NSString *)keywords
{
    [self.loadingView startAnimating];
    [self.tableView addSubview:self.bottomView];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.dataSource removeAllObjects];
        [self.tableView reloadData];
        
        [self.requestTool loadEquipmentListByPage:1 size:99999 status:@"" actStatus:@"" str:keyword isNeedDeptId:YES show:NO success:^(NSArray *equipments,NSArray *equipCounts) {
            [self.loadingView stopAnimating];
            [self.bottomView removeFromSuperview];
            
            self.dataSource = [NSMutableArray arrayWithArray:equipments];
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            PPLog(@"load eq list error = %@",error);
        }];
    });
}

- (UILabel *)tipLabel
{
    if (_tipLabel == nil) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake((kScreenWidth - 200) / 2, kScreenHeight / 2 - 30, 200, 30)];
        _tipLabel.text = @"未找到相关内容";
        _tipLabel.font = [UIFont systemFontOfSize:15];
        
        if (@available(iOS 13.0, *)) {
            UIColor *tipColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
                if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                    return kTextLightBlackColor;
                } else {
                    return kTextGrayColor;
                }
            }];
            _tipLabel.textColor = tipColor;
        } else {
            _tipLabel.textColor = kTextLightBlackColor;
        }
        
        _tipLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _tipLabel;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.dataSource.count && !self.isEmpty && !self.loadingView.isAnimating) {
        [tableView addSubview:self.tipLabel];
    } else {
        [self.tipLabel removeFromSuperview];
    }
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:kSearchCellIdentifier];
    EquipmentModel *model = self.dataSource[indexPath.row];
    
    [cell updateAttributedTextWithModel:model keyword:keyword];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    EquipmentModel *eqModel = self.dataSource[indexPath.row];
//    PPLog(@"%@==%@",eqModel.point[@"lat"],eqModel.point[@"lng"]);
    if ([eqModel.pointModel.lat isKindOfClass:[NSNull class]] || [eqModel.pointModel.lng isKindOfClass:[NSNull class]] )
    {
        [[[UIAlertView alloc]initWithTitle:@"该设备未定位" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    
    if ([eqModel.mark isEqualToString:@"D"]) {
        [[[UIAlertView alloc] initWithTitle:@"该设备已被禁用" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    
    CLLocationCoordinate2D selectedCoord = CLLocationCoordinate2DMake([eqModel.pointModel.lat doubleValue], [eqModel.pointModel.lng doubleValue]);
    if (self.delegate && [self.delegate respondsToSelector:@selector(annotationFromSearchTableViewCell:)]) {
        [self.delegate annotationFromSearchTableViewCell:selectedCoord];
    }
    [self cancelAction];
}

- (void)cancelAction
{
    [self.searchView.textField resignFirstResponder];
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setWhiteNavigationBar];
    [self.searchView.textField becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.searchView.textField resignFirstResponder];
}

- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (UIView *)bottomView
{
    if (_bottomView == nil) {
        _bottomView = [[UIView alloc] init];
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.loadingView = loadingView;
        [loadingView startAnimating];
        [_bottomView addSubview:loadingView];
        
        UILabel *loadingLabel = [[UILabel alloc] init];
        self.loadingLabel = loadingLabel;
        loadingLabel.text = @"搜索中...";
        loadingLabel.font = SYSTEM_FONT(15);
        loadingLabel.textColor = kTextBlackColor;
        loadingLabel.textAlignment = NSTextAlignmentCenter;
        [_bottomView addSubview:loadingLabel];
        
    }
    return _bottomView;
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.bottomView.frame = CGRectMake((kScreenWidth-150)/2, 10, 130, 30);
    
    self.loadingView.sd_layout
    .leftSpaceToView(self.bottomView, 20)
    .centerYEqualToView(self.bottomView);
    
    self.loadingLabel.sd_layout
    .rightSpaceToView(self.bottomView, 20)
    .centerYEqualToView(self.bottomView)
    .widthRatioToView(self.bottomView, 0.5)
    .heightIs(30);
}

@end
